/*****************************************************************************
 *   me32g030_dma.c:  Source file for me32g030 DMA 
 *   ver 1.0
******************************************************************************/
#include "me32g030.h"
#include "me32g030_dma.h"

void DMA_Init(DMA_CHNL_CTRL_TypeDef * dmactrl)
{
	//copy vector table to SRAM 0x10000000
	uint8_t i;
	uint32_t * p1;
	uint32_t * p2;
	p1=(uint32_t *)0;
	p2=(uint32_t *)0x10000000;
	for(i=0;i<0xC0;i=i+4)
	{
		*p2=*p1;
		p1++;
		p2++;
	}
	SYSCON->SYSMEMREMAP = 1;
	//enable clock of DMA digital
	SYSCON->SYSAHBCLKCTRL_b.DMA_CLK = 1;
	//reset DMA
	SYSCON->PRESETCTRL_b.DMA_RST_N = 0;
	SYSCON->PRESETCTRL_b.DMA_RST_N = 1;
	DMA->CTRL_BASE_PTR  = (uint32_t) dmactrl; //set up DMA chnl ctrl base pointer
	DMA->DMA_CFG_b .MASTER_EN = 1;
  return;
}
void DMA_Channel_CFG(DMA_CHNL_CTRL_TypeDef* dmactrl,uint8_t chn,uint16_t nooftimes,uint8_t width,uint32_t srcaddr,uint32_t dstaddr,uint8_t srcaddrtype,uint32_t dstaddrtype)
{
	dmactrl[chn].CHNL_CTRL_b.cycleCtrl =1;
	dmactrl[chn].CHNL_CTRL_b.srcSize =width;
	dmactrl[chn].CHNL_CTRL_b.srcInc = width|srcaddrtype; 
	dmactrl[chn].CHNL_CTRL_b.dstSize = width;
	dmactrl[chn].CHNL_CTRL_b.dstInc =width|dstaddrtype; 
	dmactrl[chn].CHNL_CTRL_b.nMinus1 = nooftimes-1;
	dmactrl[chn].SRC_END_PTR = srcaddr; 
	dmactrl[chn].DES_END_PTR = dstaddr;
	if (srcaddrtype==DMA_ADDR_INC)
		dmactrl[chn].SRC_END_PTR += (1<<width)*(nooftimes-1); 
	if (dstaddrtype==DMA_ADDR_INC)
		dmactrl[chn].DES_END_PTR += (1<<width)*(nooftimes-1);
  return;
}
void DMA_Channel_Enable(uint8_t chn,uint8_t priority,uint8_t irqen)
{
	uint32_t chnmask;
	chnmask=1<<chn;
	DMA->CHNL_ENABLE_SET |= chnmask;
	if (priority)
		DMA->CHNL_PRIORITY_SET |= chnmask;
	else
		DMA->CHNL_PRIORITY_CLR |= chnmask;
	if (irqen)
		DMA->CHNL_IRQ_ENABLE |= chnmask;
	else
		DMA->CHNL_IRQ_ENABLE &= ~chnmask;
  return;
}
void DMA_Channel_Disable(uint8_t chn)
{
	uint32_t chnmask;
	chnmask=1<<chn;
	DMA->CHNL_ENABLE_CLR |= chnmask;
	DMA->CHNL_PRIORITY_CLR |= chnmask;
  return;
}
void DMA_Clr_INT_Statu(uint8_t chn)
{
	DMA->CHNL_IRQ_STATUS = 1<<chn;
  return;
}
